import json
import requests
import os
import logging
from pathlib import Path
from natsort import natsorted
from tkinter import filedialog


class WechatPublisher:
    """
    将图片推送到公众号后台生成草稿
    """

    def __init__(self, appid, secret, folder_path):
        """
        初始化微信公众号发布器
        :param appid: 微信公众号的AppID
        :param secret: 微信公众号的AppSecret
        :param folder_path: 存放图片的文件夹路径
        """
        self.logger = None
        self.appid = appid
        self.secret = secret
        self.access_token = None
        self.setup_logging()
        self.folder_path = folder_path

    def setup_logging(self):
        """设置日志配置"""
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s'
        )
        self.logger = logging.getLogger(__name__)

    def get_access_token(self):
        """获取访问令牌"""
        url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={self.appid}&secret={self.secret}"
        try:
            response = requests.get(url)
            result = response.json()
            if 'access_token' in result:
                self.access_token = result['access_token']
                return self.access_token
            else:
                self.logger.error(f"获取access_token失败: {result}")
                raise Exception(f"获取access_token失败: {result}")
        except Exception as e:
            self.logger.error(f"获取access_token时发生错误: {str(e)}")
            raise

    def upload_image(self, image_path):
        """
        上传单张图片到微信服务器
        :param image_path: 图片文件路径
        :return: 媒体ID
        """
        if not self.access_token:
            self.get_access_token()

        url = f"https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={self.access_token}"

        try:
            with open(image_path, 'rb') as f:
                files = {'media': f}
                response = requests.post(url, files=files)
                result = response.json()

                if 'url' in result:
                    return result['url']
                else:
                    self.logger.error(f"上传图片失败: {result}")
                    raise Exception(f"上传图片失败: {result}")
        except Exception as e:
            self.logger.error(f"上传图片时发生错误: {str(e)}")
            raise

    def batch_upload_images(self, image_paths):
        """批量上传图片到公众号后台"""

        # 获取文件夹中的所有图片文件
        image_files = natsorted([f for f in os.listdir(image_paths) if f.endswith(('.png', '.jpg', '.jpeg'))])

        # 用于存放上传后的图片地址
        img_urls = []

        for image_file in image_files:
            image_path = os.path.join(image_paths, image_file)
            # 上传并获取返回后的url
            img_url = self.upload_image(image_path)
            img_urls.append(img_url)

        return img_urls

    def get_mid(self, access_token):
        """
        获取素材列表
        """
        # 请求的 URL
        url = f'https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={access_token}'

        # 请求体参数
        data = {
            "type": "image",  # 素材类型
            "offset": 0,  # 偏移量
            "count": 10  # 获取数量
        }

        # 发送 POST 请求
        response = requests.post(url, json=data)
        response.encoding = 'utf-8'
        print(response.text)
        # 解析响应数据
        data = response.json()

        # 检查返回的素材数据
        if 'item' in data:
            for item in data['item']:
                print(f"媒体ID: {item['media_id']}, 文件名: {item['name']}, URL: {item['url']}")
            return data['item']
        else:
            print(f"请求失败，错误信息: {data.get('errmsg')}")

    def create_draft(self, media_id):
        """
        创建单篇草稿
        """
        if not self.access_token:
            self.get_access_token()

        url = f"https://api.weixin.qq.com/cgi-bin/draft/add?access_token={self.access_token}"

        headers = {
            'Content-Type': 'application/json; charset=utf-8'
        }

        # 格式化文章内容，添加必要的HTML标签
        formatted_content = ""
        for image_path in self.batch_upload_images():
            formatted_content += f"""
                <img src="{image_path}" />
            """

        title = Path(self.folder_path).name

        try:
            # 上传所有图片
            articles = {
                "articles": [{
                    "title": title,
                    "content": formatted_content,
                    "author": "羊驼叨叨叨",
                    "thumb_media_id": media_id,
                    "digest": "",
                }]
            }

            json_content = json.dumps(articles, ensure_ascii=False)

            response = requests.post(url, data=json_content.encode('utf-8'), headers=headers)
            response.encoding = 'utf-8'

            result = response.json()

            print(result)

            if result.get('media_id'):
                self.logger.info(f"成功创建草稿: {title}")
                return result.get('media_id')
            else:
                self.logger.error(f"创建草稿失败: {result}")
                raise Exception(f"创建草稿失败: {result}")

        except Exception as e:
            self.logger.error(f"创建草稿时发生错误: {str(e)}")
            raise

    def create_draft_batch(self, media_id, folder_path):
        """
        批量创建公众号草稿
        :param media_id: 封面图片id
        :return: 成功
        """
        if not self.access_token:
            self.get_access_token()
        url = f"https://api.weixin.qq.com/cgi-bin/draft/add?access_token={self.access_token}"

        headers = {
            'Content-Type': 'application/json; charset=utf-8'
        }

        # 构建一个空的articles用于存放文章草稿
        articles = {
            "articles": []
        }

        # 列出指定路径下的所有文件和文件夹
        items = os.listdir(folder_path)
        # 过滤出文件夹
        folders = [f for f in items if os.path.isdir(os.path.join(folder_path, f))]

        for folder in folders:

            item_folder_path = os.path.join(folder_path, folder)
            print(item_folder_path)

            # 格式化文章内容，添加必要的HTML标签
            formatted_content = ""
            for image_path in self.batch_upload_images(item_folder_path):
                formatted_content += f"""
                    <img src="{image_path}" />
                """

            try:
                # 构建草稿

                title = Path(item_folder_path).name

                article_item = {
                    "title": title,
                    "content": formatted_content,
                    "author": "羊驼叨叨叨",
                    "thumb_media_id": media_id,
                    "digest": "",
                }

                articles["articles"].append(article_item)

            except Exception as e:
                self.logger.error(f"创建草稿时发生错误：: {str(e)}")

        print(articles)

        # 请求接口创建草稿
        json_content = json.dumps(articles, ensure_ascii=False)
        response = requests.post(url, data=json_content.encode('utf-8'), headers=headers)

        result = response.json()
        print(result)

        if result.get('media_id'):
            self.logger.info(f"成功创建草稿")
            return result.get('media_id')

        else:
            self.logger.error(f"创建爱你草稿失败：{result}")
            raise Exception(f"创建草稿失败{result}")


if __name__ == '__main__':
    appid = "your_appid"
    secret = "your_secret"
    media_id = "-5pV2yJQlC6HyiRIKb-zgEPJMuQkzhK6j6vXXZHuVDOxlltxbpq5dKB3Ye848AcV"
    folder_path = filedialog.askdirectory(title="请选择图片文件夹")

    # 示例使用
    wechat_publisher = WechatPublisher(appid, secret, folder_path)

    # 调用类方法
    wechat_publisher.create_draft_batch(media_id, folder_path)
